package implicits

import argonaut.{DecodeJson, DecodeResult, EncodeJson, Json}
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import play.api.http.{ContentTypeOf, ContentTypes, Writeable}
import play.api.mvc.Codec

/**
 * Created by yz on 11/4/2022
 */
trait ArgonautExtraTool {

  implicit def encodeDateTime: EncodeJson[DateTime] =
    EncodeJson.of[String].contramap(y => y.toString("yyyy-MM-dd HH:mm:ss"))

  implicit def decodeDateTime: DecodeJson[DateTime] = {
    DecodeJson { c =>
      c.as[String].flatMap { s =>
        val formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
        DecodeResult.ok(formatter.parseDateTime(s))
      }
    }
  }

  implicit def contentTypeOf_ArgonautJson(implicit codec: Codec): ContentTypeOf[argonaut.Json] = {
    ContentTypeOf[argonaut.Json](Some(ContentTypes.JSON))
  }

  implicit def writeableOf_ArgonautJson(implicit codec: Codec): Writeable[argonaut.Json] = {
    Writeable(jsval => codec.encode(jsval.toString))
  }


}
